/// Elegance控件库的文本控件
///
/// 简洁的文本组件，支持主题样式、文本格式化、点击事件等功能

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../core/elegance_theme.dart';

/// 文本主题类型枚举
enum ETextType {
  /// 主要文本
  primary,

  /// 错误文本
  error,

  /// 成功文本
  success,

  /// 警告文本
  warning,

  /// 信息文本
  info,
}

/// 文本装饰类型枚举
enum ETextDecoration {
  /// 无装饰
  none,

  /// 下划线
  underline,

  /// 删除线
  lineThrough,

  /// 上划线
  overline,
}

/// 文本对齐方式枚举
enum ETextAlign {
  /// 左对齐
  left,

  /// 居中对齐
  center,

  /// 右对齐
  right,

  /// 两端对齐
  justify,
}

/// 文本控件
class EText extends StatelessWidget {
  /// 创建文本控件
  const EText(
      this.text, {
        super.key,
        this.type,
        this.bold = false,
        this.size,
        this.color,
        this.decoration = ETextDecoration.none,
        this.lineHeight,
        this.align = ETextAlign.left,
        this.maxLines,
        this.overflow = TextOverflow.visible,
        this.margin,
        this.prefixIcon,
        this.suffixIcon,
        this.onTap,
      });

  /// 文本内容
  final String text;

  /// 主题颜色类型
  final ETextType? type;

  /// 是否粗体
  final bool bold;

  /// 字体大小
  final double? size;

  /// 文本颜色
  final Color? color;

  /// 文本装饰
  final ETextDecoration decoration;

  /// 行高
  final double? lineHeight;

  /// 对齐方式
  final ETextAlign align;

  /// 最大显示行数
  final int? maxLines;

  /// 文本溢出处理
  final TextOverflow overflow;

  /// 外边距
  final EdgeInsets? margin;

  /// 前置图标
  final IconData? prefixIcon;

  /// 后置图标
  final IconData? suffixIcon;

  /// 点击事件
  final VoidCallback? onTap;

  // 获取文本颜色
  Color _getTextColor(BuildContext context, ETextType? type) {
    final theme = EleganceTheme.of(context);
    if (color != null) return color!;
    if (type == null) return theme.textPrimaryColor;

    switch (type) {
      case ETextType.primary:
        return theme.primaryColor;
      case ETextType.error:
        return theme.errorColor;
      case ETextType.success:
        return theme.successColor;
      case ETextType.warning:
        return theme.warningColor;
      case ETextType.info:
        return theme.textSecondaryColor;
    }
  }

  // 转换文本装饰
  TextDecoration _getDecoration(ETextDecoration decoration) {
    switch (decoration) {
      case ETextDecoration.underline:
        return TextDecoration.underline;
      case ETextDecoration.lineThrough:
        return TextDecoration.lineThrough;
      case ETextDecoration.overline:
        return TextDecoration.overline;
      case ETextDecoration.none:
      default:
        return TextDecoration.none;
    }
  }

  // 转换文本对齐
  TextAlign _getTextAlign(ETextAlign align) {
    switch (align) {
      case ETextAlign.center:
        return TextAlign.center;
      case ETextAlign.right:
        return TextAlign.right;
      case ETextAlign.justify:
        return TextAlign.justify;
      case ETextAlign.left:
      default:
        return TextAlign.left;
    }
  }

  @override
  Widget build(BuildContext context) {
    // 获取主题颜色
    final textColor = _getTextColor(context, type);

    // 创建文本样式
    TextStyle textStyle = TextStyle(
      color: textColor,
      fontSize: size,
      fontWeight: bold ? FontWeight.bold : FontWeight.normal,
      decoration: _getDecoration(decoration),
      height: lineHeight,
    );

    // 创建文本Widget
    Widget textWidget = Text(
      text,
      style: textStyle,
      textAlign: _getTextAlign(align),
      maxLines: maxLines,
      overflow: overflow,
      softWrap: true,
    );

    // 添加图标（如果有）
    if (prefixIcon != null || suffixIcon != null) {
      textWidget = Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (prefixIcon != null)
            Padding(
              padding: const EdgeInsets.only(right: 4),
              child: Icon(prefixIcon, size: 16, color: textColor),
            ),
          Flexible(child: textWidget),
          if (suffixIcon != null)
            Padding(
              padding: const EdgeInsets.only(left: 4),
              child: Icon(suffixIcon, size: 16, color: textColor),
            ),
        ],
      );
    }

    // 添加点击处理
    if (onTap != null) {
      textWidget = GestureDetector(onTap: onTap, child: textWidget);
    }

    // 添加外边距
    if (margin != null) {
      textWidget = Padding(padding: margin!, child: textWidget);
    }

    return textWidget;
  }
}

/// 文本格式化工具类
class ETextFormatter {
  // 禁止实例化
  ETextFormatter._();

  /// 格式化手机号，添加分隔符
  static String formatPhone(String phone) {
    final RegExp phoneRegex = RegExp(r'^1[3-9]\d{9}$');
    if (phoneRegex.hasMatch(phone)) {
      return '${phone.substring(0, 3)}-${phone.substring(3, 7)}-${phone.substring(7)}';
    }
    return phone;
  }

  /// 格式化金额，添加千分位
  static String formatPrice(String price) {
    final double? num = double.tryParse(price);
    if (num != null) {
      return num.toStringAsFixed(
        2,
      ).replaceAllMapped(RegExp(r'\B(?=(\d{3})+(?!\d))'), (match) => ',');
    }
    return price;
  }

  /// 姓名脱敏
  static String maskName(String name) {
    if (name.length > 1) {
      final String firstChar = name.substring(0, 1);
      final String lastChar = name.substring(name.length - 1);
      final String stars = '*' * (name.length - 2);
      return firstChar + stars + lastChar;
    }
    return name;
  }

  /// 拨打电话
  static Future<void> makePhoneCall(String phone) async {
    final Uri phoneUri = Uri(scheme: 'tel', path: phone.replaceAll('-', ''));
    if (await canLaunchUrl(phoneUri)) {
      await launchUrl(phoneUri);
    }
  }

  /// 打开链接
  static Future<void> openLink(String url) async {
    final Uri urlUri = Uri.parse(url);
    if (await canLaunchUrl(urlUri)) {
      await launchUrl(urlUri, mode: LaunchMode.externalApplication);
    }
  }
}
